import apiClient from "@/lib/interceptor";
import moment from 'moment';

// 定义公告接口类型
export interface AnnouncementItem {
  id: number;
  deptId: number;
  deptName: string;
  deptType?: number;
  title: string;
  content: string;
  publishTime: string;
}

export interface AnnouncementResponse {
  code: number;
  msg: string;
  data: AnnouncementItem[] | null;
}

// 查询部门公告
export const getAnnouncement = async (params?: { deptId?: number; deptType?: number }) => {
  // 确保参数正确，即使是undefined也会被正确处理
  const queryParams = params || {};
  
  console.log('【API调用】getAnnouncement - 请求参数:', queryParams);
  const response = await apiClient.get('/announcement', { params: queryParams });
  
  // 优化日志打印，特别处理没有公告的情况
  if (response.data && response.data.code === 0) {
    console.log('【API调用】getAnnouncement - 没有公告:', response.data.data);
  } else {
    console.log('【API调用】getAnnouncement - 响应结果:', response.data);
  }
  
  return response.data;
};

// 上传部门公告
export const uploadAnnouncement = (data: {
  deptId: number;
  deptType: number;
  title: string;
  content: string;
  publishTime: string;
}) => {
  const formattedData = {
    ...data,
    publishTime: moment(data.publishTime).format('YYYY-MM-DDTHH:mm:ss')
  };
  console.log('【API调用】uploadAnnouncement - 请求参数:', formattedData);
  return apiClient.post('/announcement', formattedData).then(response => {
    console.log('【API调用】uploadAnnouncement - 响应结果:', response.data);
    return response;
  }).catch(error => {
    console.error('【API调用】uploadAnnouncement - 错误:', error);
    throw error;
  });
};

// 更新部门公告
export const updateAnnouncement = (data: {
  id: number;
  deptId?: number;
  deptType: number;
  title?: string;
  content?: string;
  publishTime?: string;
}) => {
  const formattedData = { ...data };
  if (data.publishTime) {
    formattedData.publishTime = moment(data.publishTime).format('YYYY-MM-DDTHH:mm:ss');
  }
  console.log('【API调用】updateAnnouncement - 请求参数:', formattedData);
  return apiClient.patch('/announcement', formattedData).then(response => {
    console.log('【API调用】updateAnnouncement - 响应结果:', response.data);
    return response;
  }).catch(error => {
    console.error('【API调用】updateAnnouncement - 错误:', error);
    throw error;
  });
};

// 删除部门公告
export const deleteAnnouncement = (ids: string) => {
  console.log('【API调用】deleteAnnouncement - 请求参数:', { ids });
  return apiClient.delete(`/announcement/${ids}`).then(response => {
    console.log('【API调用】deleteAnnouncement - 响应结果:', response.data);
    return response;
  }).catch(error => {
    console.error('【API调用】deleteAnnouncement - 错误:', error);
    throw error;
  });
};
